# -*- coding: utf-8 -*-
# @Time    : 2018/2/13 0:15
# @Author  : Soft
# @File    : service.py
# @Desc    : 作业管理的service
from module.models import Work, db, Page
from config import WorkUp
import logging

log = logging.getLogger('WORK SERVICE LOG')


class WorkService:
    def __init__(self):
        pass

    @staticmethod
    @db.atomic()
    def add(**work):
        return Work.insert(**work).execute()

    @staticmethod
    def do_mark(wid, score):
        """
        打分
        :param wid: 交作业记录id
        :param score: 分数
        """
        try:
            with db.atomic():
                if Work.update(work_score=int(score)).where(Work.id == wid).execute() > 0:
                    return True
                return False
        except BaseException as e:
            log.debug('打分异常--> %s' % e)
            return False

    @staticmethod
    @db.atomic()
    def remove(wid=0):
        return Work.delete_by_id(pk=wid)

    @staticmethod
    def change(wid=0, **work):
        try:
            with db.atomic():
                Work.update(**work).where(Work.id == wid).execute()
                return True
        except BaseException as e:
            log.debug('修改失败--> %s' % e)
            return False

    @staticmethod
    def work_count(year=None, sid=0):
        """
        统计学生提交记录总数 未用
        :param year:
        :param sid:
        :return:
        """
        try:
            if year:
                return Work.select().where(Work.work_uptime.startswith(year),
                                           Work.stu == sid,
                                           Work.work_status.in_([WorkUp.YJ, WorkUp.YQ])).count()
            return Work.select().count()
        except BaseException as e:
            log.debug('统计作业提交记录失败--> %s' % e)
            return 0

    @staticmethod
    def is_has(sid=0, kid=0):
        try:
            work = Work.select().where(Work.k == kid, Work.stu == sid).get()
            return True, work.to_dict()
        except BaseException as e:
            log.debug('通过sid kid查询失败 无记录--> %s' % e)
            return False, Work().to_dict()

    @staticmethod
    def pages(page=1, size=12, year='2018', k_id=None, stu_id=None, status=None):
        result = None
        if k_id and not stu_id:
            if status and int(status) >= 0:
                result = Work.select(). \
                    where(Work.k == k_id, Work.work_uptime.startswith(year), Work.work_status==status). \
                    order_by(Work.k.desc()). \
                    paginate(page, size)
                Page.total = Work.select(). \
                    where(Work.k == k_id, Work.work_uptime.startswith(year), Work.work_status==status).count()
            else:
                result = Work.select(). \
                    where(Work.k == k_id, Work.work_uptime.startswith(year)). \
                    order_by(Work.k.desc()). \
                    paginate(page, size)
                Page.total = Work.select(). \
                    where(Work.k == k_id, Work.work_uptime.startswith(year)).count()
        if stu_id and not k_id:
            if status and int(status) >= 0:
                result = Work.select(). \
                    where(Work.work_uptime.startswith(year), Work.stu == stu_id, Work.work_status==status). \
                    order_by(Work.k.desc()). \
                    paginate(page, size)
                Page.total = Work.select(). \
                    where(Work.work_uptime.startswith(year), Work.stu == stu_id, Work.work_status==status).count()
            else:
                result = Work.select(). \
                    where(Work.work_uptime.startswith(year), Work.stu == stu_id). \
                    order_by(Work.k.desc()). \
                    paginate(page, size)
                Page.total = Work.select(). \
                    where(Work.work_uptime.startswith(year), Work.stu == stu_id).count()
        if stu_id and k_id:
            if status and int(status) >= 0:
                result = Work.select(). \
                    where(Work.work_uptime.startswith(year), Work.stu == stu_id, Work.k == k_id,
                          Work.work_status == status). \
                    order_by(Work.k.desc()). \
                    paginate(page, size)
                Page.total = Work.select(). \
                    where(Work.work_uptime.startswith(year), Work.stu == stu_id, Work.k == k_id,
                          Work.work_status == status).count()
            else:
                result = Work.select(). \
                    where(Work.work_uptime.startswith(year), Work.stu == stu_id, Work.k == k_id). \
                    order_by(Work.k.desc()). \
                    paginate(page, size)
                Page.total = Work.select(). \
                    where(Work.work_uptime.startswith(year), Work.stu == stu_id, Work.k == k_id).count()
        if not stu_id and not k_id:
            if status and int(status) >= 0:
                result = Work.select(). \
                    where(Work.work_uptime.startswith(year), Work.work_status == status). \
                    order_by(Work.k.desc()). \
                    paginate(page, size)
                Page.total = Work.select(). \
                    where(Work.work_uptime.startswith(year), Work.work_status == status).count()
            else:
                result = Work.select(). \
                    where(Work.work_uptime.startswith(year)). \
                    order_by(Work.k.desc()). \
                    paginate(page, size)
                Page.total = Work.select(). \
                    where(Work.work_uptime.startswith(year)).count()
        Page.result = []
        for re in result:
            try:
                Page.result.append(re.to_dict())
            except BaseException as e:
                log.debug('记录中的课程或用户不存在--> %s' % e)
                Page.total -= 1  # 这里基本没用 只要出现异常 就还是会有问题
                continue
        Page.page = page
        Page.limit = size
        return Page.to_dict()

        # print WorkService.is_has(2, 1)[1].get('id')